<?php
namespace app\api\controller;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Controller;
use think\response\Json;
use think\Session;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Upload extends Controller
{
    protected function _initialize()
    {
        parent::_initialize();
        if (!Session::has('admin_id')) {
            $result = [
                'error'   => 1,
                'message' => '未登录'
            ];

            return json($result);
        }
    }

    /**
     * 通用图片上传接口
     * @return \think\response\Json
     */
//    public function upload()
//    {
//        $config = [
//            'size' => 2097152,
//            'ext'  => 'jpg,gif,png,bmp'
//        ];
//
//        $file = $this->request->file('file');
//
//        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
//        $save_path   = '/uploads/';
//        $info        = $file->validate($config)->move($upload_path);
//
//        if ($info) {
//            $result = [
//                'error' => 0,
//                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
//            ];
//        } else {
//            $result = [
//                'error'   => 1,
//                'message' => $file->getError()
//            ];
//        }
//
//        return json($result);
//    }
    public function upload()
    {

        $file = $this->request->file('file');
        $token = $this->getFileUploadToken();

        $upload_manager = new UploadManager();
        $file_info = $file->getInfo();
        $time = time();


        $url_name = "tsmy/goods/{$time}/".substr(md5($file_info['name']),0,12);
        list($ret,$err) = $upload_manager->putFile($token,"{$url_name}",$file_info['tmp_name']);

        if (!$err) {
            $qiniu_config = config('qiniu');
            $result = [
                'error' => 0,
                'url'   => $qiniu_config['url'].$url_name
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => "上传文件失败"
            ];
        }

        return new Json($result);
    }

    /**
     * 获得七牛上传token
     */
    public function getFileUploadToken()
    {
        $qiniu_config = config('qiniu');
        $qinniu = new Auth($qiniu_config['access_key'],$qiniu_config['secret_key']);
        $token = $qinniu->uploadToken($qiniu_config['bucket']);
        return $token;
    }
}